<template>
  <div
    v-loading="formLoading"
    class="custom-loading"
    :element-loading-spinner="loadingSpinner"
    element-loading-svg-view-box="0,0, 1024, 1024"
    element-loading-text="正在拉取表格..."
  >
    <div class="form-title">
      批量信息
      <zx-header-tip>
        <div>1、批量信息需要根据具体申请的域名信息确定；</div>
        <div>2、若需要填写多个管理账号/登录邮箱，请使用“，”隔开</div>
      </zx-header-tip>
    </div>
    <div class="box">
      <div class="item">
        <div class="label">下载模板：</div>
        <div class="value">
          <el-button icon="Download" class="mb-6" @click="download">
            下载模板
          </el-button>
          <div>1、模板可用于线下团队内部域名需求登记表格；</div>
          <div>2、填写内容时，请勿修改表头</div>
        </div>
      </div>
      <div class="item">
        <div class="label">上传文件：</div>
        <div class="value">
          <el-button
            icon="Upload"
            class="mb-6"
            :loading="uploadLoading"
            @click="upload"
          >
            上传文件
          </el-button>
          <div>仅支持.xlsx格式文件上传</div>
        </div>
      </div>
    </div>
    <div class="err-box" v-if="errs.length > 0">
      <div class="err-label">
        错误提示：
        <span
          v-if="errs.length > 1"
          class="open-icon"
          :class="{ 'open-icon-reverse': isOpenErr }"
          @click="changeOpen"
        >
          <el-icon><DArrowRight /></el-icon>
          {{ isOpenErr ? '收起' : '展开' }}
        </span>
      </div>
      <div class="err-value">
        <div class="err-item" v-for="(item, index) in errList" :key="index">
          {{ item }}
        </div>
      </div>
    </div>
    <div
      v-loading="uploadLoading"
      :element-loading-spinner="loadingSpinner"
      element-loading-svg-view-box="0,0, 1024, 1024"
      element-loading-text="正在上传..."
    >
      <iframe
        v-if="iframeUrl || formLoading"
        :src="`${baseLocationUrl}static/vika.html${iframeSearch}`"
        frameborder="0"
        class="vikaIframe"
      ></iframe>
      <div v-else class="no-iframe">
        <div>表格拉取失败</div>
        <el-button @click="createTable">点击重新获取表格</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  companyApplicationBatchVika,
  companyApplicationBatchUpload,
  companyApplicationBatchCheck
} from '@/api/dynamic-form';
import { loadingSpinner } from '@/assets/js/loadingIcon.js';
import useUserStore from '@/store/modules/user';
const VITE_APP_ENV = import.meta.env.VITE_APP_ENV;
const VITE_APP_VIKA_ENV = import.meta.env.VITE_APP_VIKA_ENV;

const props = defineProps({
  formValues: {
    type: Array,
    default: () => []
  }
});

const emits = defineEmits();

const baseLocationUrl = ref(
  window.baseLocationUrl + (VITE_APP_ENV === 'development' ? 'public/' : '')
);

const vikaId = ref(undefined); // 维格云id
const iframeUrl = ref(''); // 维格云url
const errs = ref([]);
const isOpenErr = ref(true);
const uploadLoading = ref(false);
const iframeSearch = ref('');

// 创建维格云表格
const formLoading = ref(false);
function createTable() {
  return new Promise((resolve, reject) => {
    iframeUrl.value = '';
    errs.value = [];
    isOpenErr.value = true;
    formLoading.value = true;
    companyApplicationBatchVika({ params: props.formValues })
      .then(res => {
        const resData = res.data || {};
        vikaId.value = resData.vika_doc_id;
        iframeUrl.value = `https://vika.prod.mundossp.com${resData.link}`;
        // 拼接iframe参数
        iframeSearch.value = `?iframeUrl=${iframeUrl.value}&company_id=${
          useUserStore().company_id
        }&env=${VITE_APP_VIKA_ENV}`;
        resolve();
      })
      .catch(() => {
        emits('clearVika');
        reject();
      })
      .finally(() => {
        formLoading.value = false;
      });
  });
}

// 返回数据
function returnData() {
  return new Promise((resolve, reject) => {
    if (!vikaId.value) {
      reject();
      $msg.warning('未获取到表格');
      return;
    }
    companyApplicationBatchCheck({
      params: props.formValues,
      vika_doc_id: vikaId.value
    })
      .then(res => {
        errs.value = res.data?.message || [];
        emits('changeTotal', res.data?.total || 0);
        if (errs.value.length) {
          $msg.warning('有不符合规范的内容，请调整后重试');
          reject();
        } else {
          resolve({ vikaId: vikaId.value });
        }
      })
      .catch(() => {
        reject();
      });
  });
}

// 错误相关
function changeOpen() {
  isOpenErr.value = !isOpenErr.value;
}
const errList = computed(() => {
  if (isOpenErr.value) return errs.value;
  return errs.value.slice(0, 1);
});

// 下载
function download() {
  // const baseUrl = 'https://oms.test.thierex.com';
  // window.open(
  //   `${baseUrl}/company/application/batch/download?params=${JSON.stringify(
  //     props.formValues
  //   )}`
  // );
  window.open(
    `/company/application/batch/download?params=${JSON.stringify(
      props.formValues
    )}`
  );
}

// 上传
function upload() {
  const linkDom = document.createElement('input');
  linkDom.type = 'file';
  const fileType =
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  linkDom.accept = fileType;
  linkDom.onchange = () => {
    const file = linkDom.files?.[0];
    if (!file) return;
    if (file.type !== fileType) {
      return $msg.warning('仅支持.xlsx格式文件上传');
    }
    const params = new FormData();
    params.append('file', file);
    params.append('params', JSON.stringify(props.formValues));
    params.append('vki_doc_id', vikaId.value);
    uploadLoading.value = true;
    companyApplicationBatchUpload(params)
      .then(res => {
        errs.value = res.data?.message || [];
        emits('changeTotal', res.data?.total || 0);
      })
      .finally(() => {
        uploadLoading.value = false;
      });
  };
  linkDom.click();
}

defineExpose({ createTable, returnData });
</script>

<style lang="scss" scoped>
.box {
  display: flex;
  justify-content: space-between;
  .item {
    width: 50%;
    display: flex;
    align-items: flex-start;
  }
  .label {
    line-height: 32px;
  }
  .value {
    line-height: 20px;
    font-size: 13px;
    color: #999;
  }
}
.err-box {
  color: var(--el-color-danger);
  display: flex;
  line-height: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
}
.open-icon {
  user-select: none;
  color: var(--el-color-primary);
  cursor: pointer;
  display: flex;
  align-items: center;
  height: 20px;
  width: 50px;
  margin-right: 5px;
  .el-icon {
    transform: rotate(90deg);
    line-height: 20px;
    margin-right: 3px;
    transition: all 0.2s;
  }
}

.open-icon-reverse {
  .el-icon {
    transform: rotate(-90deg);
  }
}
.err-item {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}
.vikaIframe {
  width: 100%;
  height: 500px;
}
.no-iframe {
  width: 100%;
  height: 500px;
  display: flex;
  align-content: center;
  justify-content: center;
  color: #aaa;
  border: 1px dashed #aaa;
  font-size: 18px;
  letter-spacing: 4px;
  flex-wrap: wrap;
  color: var(--el-color-danger);
  div {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-bottom: 10px;
  }
}
.err-value {
  max-height: 200px;
  overflow-y: auto;
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  word-break: break-all;
}
.err-label {
  display: flex;
  flex-wrap: nowrap;
}
</style>
